package com.mmc.delay.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class LockUtil {

    public static final Object LOCK =  new Object();
    public static final Object STOP_LOCK =  new Object();

    private static final Map<String,AtomicLong> LOCK_MAP=new ConcurrentHashMap<>();

    public static synchronized void tryUpdateTime(String partition,long newTime){
        AtomicLong nextTime = LOCK_MAP.get(partition);
        if(nextTime==null){
            LOCK_MAP.put(partition,new AtomicLong(newTime));
            return;
        }
        /**
         * 新时间比这里的NEXT_TIME小的话，唤醒阻塞
         */
      if(newTime<nextTime.get()){
          nextTime.set(newTime);
          synchronized (LOCK){
              LOCK.notifyAll();
          }
      }
    }


    public static synchronized AtomicLong getNextTime(String partition) {
        if(LOCK_MAP.get(partition)==null){
            AtomicLong atomicLong = new AtomicLong();
            LOCK_MAP.put(partition,atomicLong);
            return atomicLong;
        }
        return LOCK_MAP.get(partition);
    }
}
